package com.zwface.demo.greendao.manager;

import android.content.Context;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.zwface.demo.App;
import com.zwface.demo.greendao.DaoSession;

public class DatabaseDaoManager {
    private static DatabaseDaoMaster.OpenHelper bHelper;
    private static DatabaseDaoMaster bMaster;

    public static void initSessions(Context context,String curDbName)
    {
        //Set<String> names = DatabasePathController.getDatabasePathNames();

        if( bHelper == null ){
            synchronized(DatabaseDaoMaster.class){
                if(bHelper==null)
                    bHelper = new DatabaseDaoMaster.OpenHelper(context, curDbName);
            }
        }

        if( bMaster == null ){
            synchronized(DatabaseDaoMaster.class){
                if( bMaster == null )
                    bMaster = new DatabaseDaoMaster(bHelper.getWritableDb());
            }
        }

        DaoSession daoSession = bMaster.newSession();
        if(daoSession==null)
        {
            ToastUtils.showShort("未初始化本地数据库("+curDbName+")，请重新打开！");
            LogUtils.file("未初始化本地数据库("+curDbName+")，请重新打开！");
            return;
        }
        App.getInstance().setDaoSession(daoSession);
    }

    public static DaoSession getDaoSesson(String name) {
        DaoSession daoSession = App.getInstance().getDaoSession();
        return daoSession;
    }

    //清除单例，防止切换用户数据库相同
    public static void clearDb()
    {
        App.getInstance().setDaoSession(null);
        bHelper = null;
        bMaster = null;
    }
}
